/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package com.topisv.tms.service.account;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import javax.annotation.PostConstruct;

import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springside.modules.utils.Encodes;

import com.topisv.tms.entity.Function;
import com.topisv.tms.entity.Permission;
import com.topisv.tms.entity.Role;
import com.topisv.tms.entity.User;
import com.topisv.tms.entity.Userrole;
import com.topisv.tms.service.DepartmentService;
import com.topisv.tms.utils.DigestsUtils;
import com.topisv.tms.utils.WmsContants;

public class ShiroDbRealm extends AuthorizingRealm {
	private static final Logger log = LoggerFactory.getLogger(ShiroDbRealm.class);

	protected AccountService accountService;
	protected DepartmentService departmentService;

	@Autowired
	public void setDepartmentService(DepartmentService departmentService) {
		this.departmentService = departmentService;
	}

	/**
	 * 认证信息
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken authcToken) throws AuthenticationException {
		
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		
		User user = accountService.findUserByUsername(token.getUsername());
	
		
		if (user != null && "1".equals(user.getStatus())) { //用户存在且没有删除

			byte[] salt = Encodes.decodeHex(user.getSalt());
			
			ShiroUser shiroUser=new ShiroUser(user.getId(),
					user.getUsername(),
					user.getRealname(),
					user.getUserType(),
					user.getJobuuid(),
					user.getAreagroups(),
					user.getCustomerCode(),
					user.getCustomers());
			
			SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(shiroUser,user.getPassword(), ByteSource.Util.bytes(salt), getName());
			log.info("{}", info.toString());
			return info;
		} else {
			return null;
		}
	}

	/**
	 *  授权信息
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		
		ShiroUser shiroUser = (ShiroUser) principals.getPrimaryPrincipal();
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		
		
		
		//封装菜单
		List<Function> functions = accountService.getMenu("1");
		List<Function> menus = new ArrayList<Function>();
		
		if (null != functions) {
			for (int i = 0; i < functions.size(); i++) {
				
				Function f_1=functions.get(i);
				if ("0".equals( f_1.getRestype()+"" )) {
					
					List<Function> childs = new ArrayList<Function>();
					
					for (int j = 0; j < functions.size(); j++) {
						
						Function f_2=functions.get(j);
						if ("1".equals(f_2.getRestype() + "") && f_2.getFunction().getId().equals(f_1.getId())) { //父子关系
							
							List<Function> childs2 = new ArrayList<Function>();
							
							for (Function f_3 : functions) {
								
								if ("2".equals(f_3.getRestype() + "") && f_3.getFunction().getId().equals(f_2.getId())) {
									childs2.add(f_3);
								}
							}
							
							functions.get(j).setChildMenu(childs2);
							childs.add(functions.get(j));
						}
					}

					functions.get(i).setChildMenu(childs);
					menus.add(functions.get(i));
				}
			}
		}
		
		
		shiroUser.menus = menus;
		SecurityUtils.getSubject().getSession().setAttribute(WmsContants.USER_NAME, shiroUser.username);
		
		
		//封装角色、权限
		List<Userrole> userroles = accountService.findByUserId(shiroUser.id);
		List<Permission> permissions = null;

		HashSet<String> roleSet = new HashSet<String>();
		HashSet<String> permissionSet = new HashSet<String>();
		
		if (null != userroles) {
			
			for (int i = 0; i < userroles.size(); i++) {
				
				Role role = accountService.findRoleById(userroles.get(i).getRole().getId());
				roleSet.add(role.getRolename());
				permissions = accountService.findByRoleId(role.getId());
				if (null != permissions) {
					for (int j = 0; j < permissions.size(); j++) {
						permissionSet.add(permissions.get(j).getUrlprefix());
					}
				}
				
			}
			
		}
		
		info.setRoles(roleSet);
		info.setStringPermissions(permissionSet);
		
		return info;
	}

	/**
	 * 设定Password校验的Hash算法与迭代次数.
	 */
	@PostConstruct
	public void initCredentialsMatcher() {
		HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(
				DigestsUtils.HASH_ALGORITHM);
		matcher.setHashIterations(DigestsUtils.HASH_INTERATIONS);
		setCredentialsMatcher(matcher);
	}

	@Autowired
	public void setAccountService(AccountService accountService) {
		this.accountService = accountService;
	}

	/**
	 * 自定义Authentication对象，使得Subject除了携带用户的登录名外还可以携带更多信息.
	 */
	public static class ShiroUser implements Serializable {
		private static final long serialVersionUID = -1373760761780840081L;
		public Long id;
		public String username;
		public String realname;
		public List<Function> menus;
		public String jobuuid;
		public String customerCode;
		public String userType;//用户类型 （paiu: 派友用户 customer: 商家用户）
		public String areagroups;//区域组 （如果user_type为：paiu，此字段有效）
		public String customers;//商户组 (如果user_type为：paiu，此字段有效)

		/**
		 * 
		 * @param id
		 * @param username 用户登陆名
		 * @param realname 用户真实姓名
		 * @param userType 用户类型
		 * @param jobuuid  uuid
		 * @param areagroups 网点列表
		 * @param customerCode  商家编码
		 * @param customers 商家编码列表
		 */
		public ShiroUser(Long id, String username, String realname,String userType, String jobuuid, String areagroups,String customerCode,String customers) {
			this.id = id;
			this.username = username;
			this.realname = realname;
			this.userType = userType;
			this.jobuuid = jobuuid;
			this.areagroups = areagroups;
			this.customerCode= customerCode;
			this.customers=customers;
		}

		public String getRealname() {
			return realname;
		}
		
		public String getJobuuid(){
			return this.jobuuid;
		}

		/**
		 * 本函数输出将作为默认的<shiro:principal/>输出.
		 */
		@Override
		public String toString() {
			return username;
		}

		/**
		 * 重载equals,只计算loginName;
		 */
		@Override
		public int hashCode() {
			return HashCodeBuilder.reflectionHashCode(this, "username");
		}

		/**
		 * 重载equals,只比较loginName
		 */
		@Override
		public boolean equals(Object obj) {
			return EqualsBuilder.reflectionEquals(this, obj, "username");
		}
	}
}
